package com.atom.common.util;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sinosoft.commontools.record.Record;

/**
 * Title: JsonUtil
 * Description: 
 * @author WEWE
 * @date 2016年3月16日 上午9:45:17
 * @version 1.0
 */
public class JsonUtil {	

  private static Logger logger = Logger.getLogger(JsonUtil.class);  

  private static final String EMPTY_STRING = "";

  /**
   * Description: 将Object转成Json格式，成功则返回Json字符串，失败则返回空字符串
   * @param o
   * @return String
   */
  public static String ObjectToJsonQuietly(Object o){
    ObjectMapper mapper = new ObjectMapper(); 
    try {
      String json = mapper.writeValueAsString(o);
      return json;
    } catch (JsonProcessingException e) {
      logger.error("Json生成失败 : " + e.getMessage());
      return EMPTY_STRING;
    }
  } 

  /**
   * Description: 将Json转为指定的Object
   * @param json
   * @param clazz
   * @return 成功 返回T; 失败 返回null
   */
  public static <T> T JsonToObjectQuietly(String json, Class<T> clazz) {
    logger.info("JSON : " + json);
    ObjectMapper mapper = new ObjectMapper(); 
    T result = null;
    try {
      result = mapper.readValue(json, clazz);
    } catch (JsonParseException e) {
      logger.error("Json解析失败 : " + e.getMessage());
    } catch (JsonMappingException e) {
      logger.error("Json解析失败 : " + e.getMessage());
    } catch (IOException e) {
      logger.error("Json解析失败 : " + e.getMessage());
    }
    return result;    
  }

  /**
   * Description: 将Json转为指定的List
   * @param json
   * @param clazz
   * @return 成功 返回List<T>; 失败 返回null
   */
  public  static <T> List<T>  JsonToListQuietly(String json, Class<T[]> clazz) {
    logger.info("JSON : " + json);
    ObjectMapper mapper = new ObjectMapper(); 
    T[] result;
    try {
      result = mapper.readValue(json, clazz);
      return Arrays.asList(result);
    } catch (JsonParseException e) {
      logger.error("error message = {}" + e.getMessage(), e);
    } catch (JsonMappingException e) {
      logger.error("error message = {}" + e.getMessage(), e);
    } catch (IOException e) {
      logger.error("error message = {}" + e.getMessage(), e);
    }
    return null;
  }

  public static Record ObjectToRecord(Object obj) {
	  Record r = new Record();
	  List<Field> field =getFieldList(obj.getClass());// obj.getClass().getDeclaredFields();
	  for(Field f:field){
		  String name = f.getName();
		  if(name.equals("serialVersionUID"))
			  continue;
		  try {
			  f.setAccessible(true);
//			  //给属性设置  
//			  f.set(obj,f.getType().getConstructor(f.getType()).newInstance("kou"));
			  String methodName = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
			  Method m = obj.getClass().getMethod("get" + methodName);
			  r.add(name, m.invoke(obj));
		} catch (Exception e) {
			e.printStackTrace();
		}
	  }
	  return r;
  }
  public static Record ObjectToRecord(Object obj,Record r) {
//	  Record r = new Record();
	  List<Field> field =getFieldList(obj.getClass());// obj.getClass().getDeclaredFields();
	  for(Field f:field){
		  String name = f.getName();
		  if(name.equals("serialVersionUID"))
			  continue;
		  try {
			  f.setAccessible(true);
//			  //给属性设置  
//			  f.set(obj,f.getType().getConstructor(f.getType()).newInstance("kou"));
			  String methodName = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
			  Method m = obj.getClass().getMethod("get" + methodName);
			  r.add(name, m.invoke(obj));
		} catch (Exception e) {
			e.printStackTrace();
		}
	  }
	  return r;
  }
  
  public static List<Field> getFieldList(Class<?> clazz){
	    if(null == clazz){
	        return null;
	    }
	    List<Field> fieldList = new LinkedList<Field>();
	    Field[] fields = clazz.getDeclaredFields();
	    for(Field field : fields){
	        /** 过滤静态属性**/
	        if(Modifier.isStatic(field.getModifiers())){
	            continue;
	        }
	        /** 过滤transient 关键字修饰的属性**/
	        if(Modifier.isTransient(field.getModifiers())){
	            continue;
	        }
	        fieldList.add(field);
	    }
	    /** 处理父类字段**/
	    ;
	    Class<?> superClass = clazz.getSuperclass();
	    if(superClass.equals(Object.class)){
	        return fieldList;
	    }
	    fieldList.addAll(getFieldList(superClass));
	    return fieldList;
	}
}
